package com.jp.knowledge.adapter;


import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Handler;
import android.os.Message;
import android.util.TypedValue;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.gson.JsonObject;
import com.jiayen.util.ToasUtil;
import com.jp.knowledge.R;
import com.jp.knowledge.activity.EditHeadLineAcitvity;
import com.jp.knowledge.comm.JpApplication;
import com.jp.knowledge.dialog.DelResonDialog;
import com.jp.knowledge.http.HttpHelper;
import com.jp.knowledge.model.HeadLineData;
import com.jp.knowledge.model.IModel;
import com.jp.knowledge.util.ImageLoadUtil;
import com.jp.knowledge.util.ResultSubscriber;
import com.jp.knowledge.util.SharedUtil;
import com.jp.knowledge.util.TimeUtil;

import java.util.List;

import static android.content.Context.MODE_PRIVATE;
import static com.umeng.socialize.utils.ContextUtil.getContext;


/**
 * Created by jiangyue on 2016/4/12.
 */
public class CommtemAdapter extends JpBaseRecyViewAdapter implements ResultSubscriber.OnResultListener {

	/**
	 * 头条来源
	 **/
	public final static int SOURCE_TOUTIAO = 1;
	/***
	 * 文库来源
	 */
	public final static int SOURCE_WENKU = 2;

	/**
	 * 岗位知识来源
	 **/
	public final static int SOURCE_ZHISHI = 3;
	/**
	 * 收藏来源
	 **/
	public final static int SOURCE_COLLECTION = 4;
	public int DEFALUT_POSTION = -1;//定义默认   位置 代表之前的位置
	private DelResonDialog delDialog;

	private int curPostion;

	private int textSize;
	private JpApplication application;

	private int sourceType;//来源类型

	private SharedPreferences sharedPreferences;

	public void setSourceType(int sourceType) {
		this.sourceType = sourceType;
	}

	public CommtemAdapter(final Context context, final List infos) {
		super(context, infos);

		application = (JpApplication) ((Activity) context).getApplication();

		sharedPreferences = mContext.getSharedPreferences("NewsDetail", MODE_PRIVATE);
//        this.textSize= SharedUtil.getInstance(mContext).getCommFontSize();
		getTextSize();
		delDialog = new DelResonDialog(context);
		delDialog.setDelDone(new DelResonDialog.DelDone() {
			@Override
			public void done(int type) {
				int postion = curPostion;
				try {
					HeadLineData headLineData = (HeadLineData) getItem(postion);
					if (type == 7 && application.getUserData().getPlatformAdmin() == 1) {//内容分类错误
						Intent intent = new Intent(mContext, EditHeadLineAcitvity.class);
						intent.putExtra("infoId", headLineData.getId());
						context.startActivity(intent);
					} else {
						JsonObject param = getParams(headLineData, type);
						HttpHelper.getInstance(getContext()).closeHeadContent(param, postion, CommtemAdapter.this);
					}
				} catch (Exception e) {
					ToasUtil.toast(mContext, "分类数据有误!");
				}
			}
		});
	}

	/**
	 * 修改字体大小
	 */
	public void changeTextSize() {
//        this.textSize= SharedUtil.getInstance(mContext).getCommFontSize();
		getTextSize();
		notifyDataSetChanged();
	}

	private void getTextSize() {
		int size = sharedPreferences.getInt("textSizeLevel", 1);
		this.textSize = SharedUtil.getInstance(mContext).getCommFontSize();
		switch (size) {
			case 0:
				this.textSize = (int) (mContext.getResources().getDimension(R.dimen.min_font) + 0.5);
				break;
			case 1:
				this.textSize = (int) (mContext.getResources().getDimension(R.dimen.middle_font) + 0.5);
				break;
			case 2:
				this.textSize = (int) (mContext.getResources().getDimension(R.dimen.big_font) + 0.5);
				break;
			case 3:
				this.textSize = (int) (mContext.getResources().getDimension(R.dimen.large_font) + 0.5);
				break;
			default:
				this.textSize = (int) (mContext.getResources().getDimension(R.dimen.middle_font) + 0.5);
		}
	}

	@Override
	public int getLayoutId() {
		return R.layout.comm_item_layout;
	}

	@Override
	public void bindViewHold(JPRecycleViewHolder holder, int position) {
		renderData(holder, getItem(position), position);
	}

	protected void renderData(JPRecycleViewHolder holder, Object item, int position) {
		HeadLineData headLineData = (HeadLineData) item;
		holder.itemView.setTag(position);
		setRelevantView(holder, headLineData);
		TextView title = holder.getView(R.id.description);
		title.setText(headLineData.getTitle());//设置名称
		if (textSize != 0) {//有设置textSize的时候用textSize
			title.setTextSize(TypedValue.COMPLEX_UNIT_PX, textSize);//设置字体大小
		} else {
			title.setTextSize(TypedValue.COMPLEX_UNIT_PX, mContext.getResources().getDimension(R.dimen.middle_font));
		}
//        if (headLineData.isLook()) {
//            title.setTextColor(getContext().getResources().getColor(R.color.gray_light));
//        } else {
//            title.setTextColor(getContext().getResources().getColor(R.color.font_black_think));
//        }
		setNavType(holder, headLineData);
		setTextView((TextView) holder.getView(R.id.type), headLineData.getLabel());
		setTextView((TextView) holder.getView(R.id.author), headLineData.getSource());
		setTextView((TextView) holder.getView(R.id.address), headLineData.getAddress());
		if (sourceType == SOURCE_WENKU || sourceType == SOURCE_COLLECTION) {
			setTextView((TextView) holder.getView(R.id.time), TimeUtil.formatYearData(headLineData.getCreatetime()));
		}
//        else if(sourceType==SOURCE_COLLECTION){
//            setTextView((TextView) holder.getView(R.id.time), TimeUtil.formatYearData(headLineData.getCreatetime()));
//        }
		else {
			setTextView((TextView) holder.getView(R.id.time), TimeUtil.friendly_time(headLineData.getCreatetime()));
		}
		ImageView photo = holder.getView(R.id.photo);
		ImageView iconClose = holder.getView(R.id.icon_close);
		ImageView icon = holder.getView(R.id.desc_icon);
		ImageView icon_1 = holder.getView(R.id.desc_icon_1);
		ImageView icon_2 = holder.getView(R.id.desc_icon_2);
		ImageView icon_3 = holder.getView(R.id.desc_icon_3);
		ImageView headIcon = holder.getView(R.id.head_icon);
		ImageView[] imgs = new ImageView[3];
		imgs[0] = icon_1;
		imgs[1] = icon_2;
		imgs[2] = icon_3;
		List<HeadLineData.ImglistBean> list = headLineData.getImglist();
		LinearLayout muiltIcon = holder.getView(R.id.muilt_icon);

		if (headLineData.getLayout() == 1) {                  // 左图片
//            if(headLineData.getDesc() != null && headLineData.getDesc().trim().length() > 0){
//                holder.setText(R.id.desc_min, headLineData.getDesc());
//                holder.getView(R.id.desc_min).setVisibility(View.VISIBLE);
//            } else {
//                holder.getView(R.id.desc_min).setVisibility(View.GONE);
//            }
			photo.setVisibility(View.GONE);
			icon.setVisibility(View.GONE);
			muiltIcon.setVisibility(View.GONE);
			if (headLineData.getType() == 3) {                // 公司不显示图片
				headIcon.setVisibility(View.GONE);
			} else {
				headIcon.setVisibility(View.VISIBLE);
//                ImageLoadUtil.loadrund(context, headLineData.getIcon(), headIcon, 15);
//                ImageLoadUtil.load(context, headLineData.getIcon(), headIcon);
			}
			if (headLineData.getIcon() == null || headLineData.getIcon().trim().length() == 0) {
				if (headLineData.getType() == 3)
					headIcon.setImageResource(R.mipmap.intelligent_analytics);
				else if (headLineData.getType() == 8)
					headIcon.setImageResource(R.mipmap.intelligent_analysis_products);
				else if (headLineData.getType() == 4)
					headIcon.setImageResource(R.mipmap.intelligent_analysis_character);
				else if (headLineData.getType() == 18)
					icon.setImageResource(R.mipmap.keyword);
			} else {
				ImageLoadUtil.load(mContext, headLineData.getIcon(), headIcon);
			}
		} else {
//            holder.getView(R.id.desc_min).setVisibility(View.GONE);
			headIcon.setVisibility(View.GONE);
//            if(headLineData.getIcon() == null || headLineData.getIcon().trim().length() == 0){
//                photo.setVisibility(View.GONE);
//            } else{
//                photo.setVisibility(View.VISIBLE);
//                ImageLoadUtil.loadCircle(context, headLineData.getIcon(), photo);
//            }
			photo.setVisibility(View.GONE);
			if (headLineData.getLayout() == 2) {              // 多图文
				icon.setVisibility(View.GONE);
				if (list == null || list.size() == 0) {
					muiltIcon.setVisibility(View.GONE);
				} else {
					muiltIcon.setVisibility(View.VISIBLE);
					for (int i = 0; i < 3 && i < list.size(); i++)
						ImageLoadUtil.load(mContext, list.get(i).getSrc(), imgs[i]);
				}
			} else if (headLineData.getLayout() == 3) {       // 右图片
				muiltIcon.setVisibility(View.GONE);
				if (list == null || list.size() == 0) {
					String iconImg = headLineData.getIcon();
					if (iconImg == null || iconImg.trim().length() == 0) {
						icon.setVisibility(View.GONE);
					} else {
						icon.setVisibility(View.VISIBLE);
						ImageLoadUtil.load(mContext, iconImg, icon);
					}
				} else {
					icon.setVisibility(View.VISIBLE);
					ImageLoadUtil.load(mContext, list.get(0).getSrc(), icon);
				}
			} else if (headLineData.getLayout() == 4) {       // 纯标题
				icon.setVisibility(View.GONE);
				muiltIcon.setVisibility(View.GONE);
			}
		}

		if (headLineData.getIsFollow() == 1
				&& application.getUserData() != null
				&& application.getUserData().getIsLogin() == 1)
			holder.getView(R.id.icon_collection).setVisibility(View.VISIBLE);
		else
			holder.getView(R.id.icon_collection).setVisibility(View.GONE);
//        if(headLineData.getIsSubscribe() == 1
//                && application.getUserData() != null
//                && application.getUserData().getIsLogin() == 1)
//            holder.getView(R.id.icon_attention).setVisibility(View.VISIBLE);
//        else
//            holder.getView(R.id.icon_attention).setVisibility(View.GONE);
		holder.getView(R.id.icon_attention).setVisibility(View.GONE);

		iconClose.setVisibility(View.VISIBLE);
		iconClose.setTag(position);
		iconClose.setOnClickListener(this);

		setSomeViewVisibility(holder, headLineData);
	}

	protected void setSomeViewVisibility(final JPRecycleViewHolder holder, final HeadLineData headLineData) {
		holder.getView(R.id.photo).setVisibility(View.GONE);
		holder.getView(R.id.author).setVisibility(View.GONE);
		holder.getView(R.id.address).setVisibility(View.GONE);
		holder.getView(R.id.relevant_view).setVisibility(View.GONE);
		holder.getView(R.id.relevant_text).setVisibility(View.GONE);
		if (sourceType == SOURCE_COLLECTION) {
			holder.getView(R.id.icon_collection).setVisibility(View.GONE);
		}

		holder.getItemView().getViewTreeObserver().addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
			@Override
			public boolean onPreDraw() {
				holder.getItemView().getViewTreeObserver().removeOnPreDrawListener(this);
				View rightImg = holder.getView(R.id.desc_icon);
				if (headLineData.getLayout() == 3 && rightImg.getVisibility() == View.VISIBLE)
					holder.getView(R.id.item_main_layout).setMinimumHeight(rightImg.getMeasuredHeight());
				else
					holder.getView(R.id.item_main_layout).setMinimumHeight(0);
				return false;
			}
		});
	}

	private void setNavType(JPRecycleViewHolder holder, HeadLineData headLineData) {
		TextView navTextView = holder.getView(R.id.navType);
		setTextView(navTextView, headLineData.getNavType());
//        try{
//            String navColor = headLineData.getNavColor();
//            if(!navColor.startsWith("#"))
//                navColor = "#" + navColor;
//            navTextView.setTextColor(Color.parseColor(navColor));
//        } catch (Exception e){
//            navTextView.setTextColor(context.getResources().getColor(R.color.blue));
//        }
	}

	private void setRelevantView(JPRecycleViewHolder holder, HeadLineData headLineData) {
		LinearLayout relevantView = holder.getView(R.id.relevant_view);
		TextView relevantTextView = holder.getView(R.id.relevant_text);
		if (headLineData.getLayout() == 1
				|| headLineData.getRelevantInfoList() == null
				|| headLineData.getRelevantInfoList().size() == 0) {
			relevantView.setVisibility(View.GONE);
			relevantTextView.setVisibility(View.GONE);
		} else if (headLineData.getRelevantInfoList().size() == 1) {
			relevantView.setVisibility(View.VISIBLE);
			relevantTextView.setVisibility(View.GONE);
			setRelevantItem(relevantView.findViewById(R.id.relevant_item_1), headLineData.getRelevantInfoList().get(0));
		} else {
			relevantView.setVisibility(View.GONE);
			relevantTextView.setVisibility(View.VISIBLE);
			String relevantText = "";
			for (int i = 0; i < headLineData.getRelevantInfoList().size(); i++) {
				HeadLineData.RelevantInfoListBean relevantInfoListBean = headLineData.getRelevantInfoList().get(i);
				if (relevantInfoListBean != null && relevantInfoListBean.getRelevantTitle() != null
						&& relevantInfoListBean.getRelevantTitle().trim().length() > 0) {
					relevantText += relevantInfoListBean.getRelevantTitle() + ",";
				}
			}
			if (relevantText.endsWith(","))
				relevantText = relevantText.substring(0, relevantText.length() - 1);
			relevantTextView.setText(relevantText);
		}
	}

	private void setRelevantItem(View relevantItem, HeadLineData.RelevantInfoListBean relevantInfoListBean) {
		if (relevantInfoListBean == null) {
			relevantItem.setVisibility(View.INVISIBLE);
			return;
		}
		relevantItem.setVisibility(View.VISIBLE);
		ImageView iconImage = (ImageView) relevantItem.findViewById(R.id.relevant_icon_img);
		TextView iconText = (TextView) relevantItem.findViewById(R.id.relevant_icon_text);
		;
		TextView title = (TextView) relevantItem.findViewById(R.id.relevant_title);
		TextView desc = (TextView) relevantItem.findViewById(R.id.relevant_desc);
		String relevantIcon = relevantInfoListBean.getRelevantIcon();
		String relevantTitle = relevantInfoListBean.getRelevantTitle();
		if (relevantIcon != null && relevantIcon.trim().length() > 0) {
			iconImage.setVisibility(View.VISIBLE);
			iconText.setVisibility(View.GONE);
			ImageLoadUtil.loadrund(mContext, relevantIcon, iconImage, 10);
		} else if (relevantTitle != null && relevantTitle.length() > 0) {
			iconImage.setVisibility(View.GONE);
			iconText.setVisibility(View.VISIBLE);
			if (relevantInfoListBean.getRelevantType() == 3)         // 公司
				iconText.setBackground(mContext.getResources().getDrawable(R.drawable.relevant_icon_blue));
			else if (relevantInfoListBean.getRelevantType() == 4)    // 人物
				iconText.setBackground(mContext.getResources().getDrawable(R.drawable.relevant_icon_orange));
			else
				iconText.setBackground(mContext.getResources().getDrawable(R.drawable.relevant_icon_green));
			iconText.setText(relevantTitle.substring(0, 1));
		} else {
			iconImage.setVisibility(View.GONE);
			iconText.setVisibility(View.GONE);
		}
		setTextView(title, relevantTitle);
		setTextView(desc, relevantInfoListBean.getRelevantSource());
	}

	protected void setTextView(TextView textView, String text) {
		if (text == null || text.trim().length() == 0) {
			textView.setVisibility(View.GONE);
		} else {
			textView.setText(text);
			textView.setVisibility(View.VISIBLE);
		}
	}

	@Override
	public void onClick(View view) {
		if (view.getId() == R.id.icon_close) {
			deleteIconClick(view);
		} else {
			super.onClick(view);
		}
	}

	private JsonObject getParams(HeadLineData headLineData, int type) {
		JsonObject obj = new JsonObject();
		obj.addProperty("id", headLineData.getId());
		obj.addProperty("type", headLineData.getType());
		obj.addProperty("closeType", type);
		return obj;
	}

	@Override
	public void onStart(int requestType) {

	}

	@Override
	public void onCompleted(int requestType) {

	}

	@Override
	public void onError(int requestType) {
		ToasUtil.toast(mContext, "删除错误");
	}

	@Override
	public void onNext(IModel data, int requestType) {
		int success = data.getErrcode();
		if (success == 0) {
			removeSelectItem(requestType);
		} else {
			ToasUtil.toast(mContext, "删除错误");
		}
	}

	protected void deleteIconClick(View view) {
		curPostion = (int) view.getTag();
		int[] localtion = new int[2];
		view.getLocationOnScreen(localtion);
		int x = localtion[0] + view.getWidth();
		int y = localtion[1];
		delDialog.show(x, y - 20);
	}

	/**
	 * 删除  指定位置item
	 *
	 * @param postion
	 */
	public void removeSelectItem(int postion) {
		if (delDialog.isShowing()) {
			delDialog.dismiss();
		}
		postion = postion == DEFALUT_POSTION ? curPostion : postion;
		removeItem(postion);
		handler.postDelayed(new Runnable() {
			@Override
			public void run() {
				handler.sendEmptyMessage(0);
			}
		}, 500);
	}

	/**
	 * 改变看过的内容颜色
	 *
	 * @param position
	 */
	public void updateTitleColor(int position) {
//        HeadLineData headLineData = (HeadLineData) getItem(position);
//        headLineData.setLook(true);
//        notifyDataSetChanged();
	}

	private Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			notifyDataSetChanged();
		}
	};
}
